<template>
  <AdVxeTable
    @register="registerTable"
    @checkbox-change="
      () => {
        hasRowSelected = getSelectedRows()?.length > 0;
      }
    "
  >
    <template #tools>
      <Authority :value="'Root.IoT.Admin.DeviceState.Delete'">
        <a-button
          type="primary"
          color="error"
          :disabled="!hasRowSelected"
          @click="handleDeleteBatch"
        >
          <Icon icon="ant-design:delete-outlined" />{{ t('common.delText') }}
        </a-button>
      </Authority>
    </template>
    <template #actionCol="{ row }">
      <TableAction
        outside
        :actions="[
          {
            icon: 'clarity:details-line',
            tooltip: t('common.detailText'),
            onClick: handleReadDetail.bind(null, row),
          },
          {
            icon: 'ant-design:delete-outlined',
            color: 'error',
            tooltip: t('common.delText'),
            auth: 'Root.IoT.Admin.DeviceState.Delete', // 权限控制
            // ifShow: (_action) => {
            //   return row.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
            // },
            popConfirm: {
              title: t('common.delConfirmText'),
              placement: 'left',
              confirm: handleDelete.bind(null, row),
            },
          },
        ]"
      />
    </template>
  </AdVxeTable>
</template>

<script lang="ts" setup>
  import { ref, h, watch } from 'vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import Icon from '@/components/Icon/Icon.vue';

  import { FilterGroup } from '#/request';
  import { propTypes } from '@/utils/propTypes';

  import { Authority } from '@/components/Authority';
  import { AdVxeTable, useAdVxeTable, TableAction, AdColumn } from '@/components/AdVxeTable';
  import { FormModeEnum } from '@/enums/formEnum';
  import { readDeviceState, deleteDeviceState } from '@/api/iot/admin/devicestate';

  import { columns } from './device.data';

  defineOptions({ name: 'DeviceStateTable' });

  const props = defineProps({
    /** 额外的搜索参数 */
    searchInfo: {
      type: Object as PropType<FilterGroup>,
      default: null,
    },
    /** 唯一标识 */
    id: propTypes.string.def('iot-state-device-page-table'),
    /** 隐藏列 */
    hideCols: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
  });

  const { t } = useI18n();
  const { createConfirm, createMessage } = useMessage();

  const hasRowSelected = ref(false);

  function getColumns() {
    let cols: AdColumn[] = [];
    columns.forEach((value, _index) => {
      let col = { ...value };
      if (value.field && props.hideCols?.length > 0) {
        col.visible = !props.hideCols.includes(value.field);
      }
      // else {
      //   col.visible = value.visible != false;
      // }
      cols.push(col);
    });
    return cols;
  }

  const [registerTable, { getTable, reload, openDetailForm, setProps, setLoading }] = useAdVxeTable(
    {
      id: props.id,
      // 表标题呈现器
      title: t('iot.route.state.device.listTitle'),
      // 表格数据接口请求对象
      api: readDeviceState,
      // 详情表单
      detailForm: {
        // 表单标识
        formIndex: 'iot_devicestate_detail',
        // 主键字段
        keyField: 'Id',
        // 详情表单抬头
        title: t('iot.route.state.device.title'),
      },
      // 表单列信息 AdColumn[]
      columns: getColumns(),
      // 使用搜索表单
      searchForm: true,
      // 行选择设置
      selection: 'checkbox',
      // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
      border: false,
      // 是否显示序号列
      showSeqColumn: true,
      // 表格右侧操作列配置 AdColumn
      actionColumn: {
        width: 80,
        title: t('common.actionText'),
        fixed: 'right',
        slots: { default: 'actionCol' },
      },
    },
  );

  function getSelectedRows() {
    const $table = getTable();
    if ($table) {
      const rows = $table.getCheckboxRecords();
      return rows;
    }
    return [];
  }
  function clearSelectedRows() {
    const $table = getTable();
    if ($table) {
      $table.clearCheckboxRow();
    }
  }

  /** 查看详情 */
  async function handleReadDetail(record: any) {
    openDetailForm(FormModeEnum.ReadOnly, record);
  }

  /** 处理删除 */
  async function handleDelete(record: any) {
    try {
      setLoading(true);
      const result = await deleteDeviceState([record.Id]);
      if (result.Succeeded) {
        createMessage.success(t('common.successText'));
        reload();
        clearSelectedRows();
      }
    } finally {
      setLoading(false);
    }
  }
  /** 处理批量删除 */
  async function handleDeleteBatch() {
    const selectedRows = getSelectedRows();
    if (selectedRows?.length > 0) {
      createConfirm({
        zIndex: 999999999,
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('common.delConfirmText')),
        onOk: async () => {
          try {
            setLoading(true);
            const recordIds = selectedRows.map((item) => {
              return item.Id;
            });
            const result = await deleteDeviceState(recordIds);
            if (result.Succeeded) {
              createMessage.success(t('common.successText'));
              await reload();
              clearSelectedRows();
            }
          } finally {
            setLoading(false);
          }
        },
      });
    }
  }

  /** 处理搜索参数 */
  async function handleSearchInfo(searchInfo?: FilterGroup) {
    setProps({ searchInfo: searchInfo });
    await reload();
  }

  //监听数据变化
  watch(
    () => props.searchInfo,
    async () => {
      await handleSearchInfo(props.searchInfo);
    },
  );
  watch(
    () => props.id,
    () => {
      setProps({ id: props.id });
    },
  );
  watch(
    () => props.hideCols,
    () => {
      const cols = getColumns();
      setProps({ columns: cols });
    },
  );
</script>
